package com.bbzn.user.client.controller;

import com.bbzn.user.client.aspect.OperationAnnotation;
import com.bbzn.user.client.constant.RoleConstant;
import com.bbzn.user.client.service.*;
import com.bbzn.user.client.vo.req.IdListVO;
import com.bbzn.user.client.constant.CrudConstant;
import com.bbzn.user.client.constant.PermissionConstant;
import com.bbzn.user.client.dataobject.Permission;
import com.bbzn.user.client.dataobject.RolePermission;
import com.bbzn.user.client.dataobject.SystemParam;
import com.bbzn.user.client.dto.permission.PermissionDTO;
import com.bbzn.user.client.exception.DefinitException;
import com.bbzn.user.client.utils.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Author wulongbo
 * @Date 2021/11/3 11:41
 * @Version 1.0
 */

@RestController
@RequestMapping("/per")
@Slf4j
@Api(value = "permission", tags = "资源管理器")
public class PermissionController extends BaseApiService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserRoleService userRoleService;


    @PostMapping("/getPermission")
    @OperationAnnotation(content = "获取资源")
    public BaseResponse getPermission(HttpServletRequest request) throws Exception {
        Long id = commonService.getUserId(request);
        List<PermissionDTO> p = permissionService.selectTreeByUserId(id);
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), p);
    }

    @PostMapping("/getPermissionByPermId")
    @OperationAnnotation(content = "根据资源id获取资源详情")
    public BaseResponse getPermissionByPermId(HttpServletRequest request, @RequestBody Permission permission) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(permission.getId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        Permission p = permissionService.selectByPrimaryKey(permission.getId());
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), p);
    }

    @PostMapping("/getNavigationBar")
    @OperationAnnotation(content = "获取导航栏")
    public BaseResponse getNavigationBar(HttpServletRequest request) throws Exception {
        Long id = commonService.getUserId(request);
        List<Permission> p = permissionService.getNavigationBar(id);
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), p);
    }

    @PostMapping("/getRolePermission")
    @OperationAnnotation(content = "获取角色拥有的权限列表")
    public BaseResponse getRolePermission(HttpServletRequest request, @RequestBody RolePermission rp) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(rp.getRoleId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(RoleConstant.ROLE_ENUM, RoleConstant.ROLE_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        Long id = commonService.getUserId(request);
        List<PermissionDTO> p = permissionService.getRolePermission(rp.getRoleId(), id);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), p);
    }

    @PostMapping("/getDefaultPermission")
    @OperationAnnotation(content = "获取默认角色的权限列表")
    public BaseResponse getDefaultPermission(HttpServletRequest request) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long id = commonService.getUserId(request);
        List<PermissionDTO> p = permissionService.getRolePermission(RoleConstant.ROLE_DEFAULT_ID, id);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), p);
    }

    @PostMapping("/addPermission")
    @OperationAnnotation(content = "新增资源")
    public BaseResponse addPermission(HttpServletRequest request, @RequestBody Permission permission) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long id = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(permission.getPid()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_PID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(permission.getName()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_NAME_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(permission.getEnName()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_EN_NAME_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(permission.getTag()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_TAG_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(permission.getType()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_TYPE_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(permission.getStatus()).isPresent()) {
            permission.setStatus(0);
        }
        if (!OptionalBean.ofNullable(permission.getUrl()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PERMISSION_NO_PATH_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        //tag+url唯一校验
        Permission check = new Permission();
        check.setTag(permission.getTag());
        check.setUrl(permission.getUrl());
        List<Permission> checkPermission = permissionService.findByAll(check);
        if (!CollectionUtils.isEmpty(checkPermission)) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_REPEAT_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        permission.setSort(permissionService.getMaxSort() + 1);
        permission.setCreateTime(new Date());
        permission.setCreatedBy(MayiktJwtUtils.getUsername(request, secretKey));
        permissionService.insert(permission);

        Integer roleId = userRoleService.getRoleIdByUserId(id);
        RolePermission insert = new RolePermission();
        insert.setPermId(permission.getId());
        insert.setRoleId(roleId);
        rolePermissionService.insert(insert);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.ADD_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());

    }

    @PostMapping("/delPermission")
    @OperationAnnotation(content = "删除资源")
    public BaseResponse delPermission(HttpServletRequest request, @RequestBody IdListVO idListVO) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long id = commonService.getUserId(request);
        if (CollectionUtils.isEmpty(idListVO.getIds())) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        Integer roleId = userRoleService.getRoleIdByUserId(id);
        // 查询是否有与该资源关联的角色
        List<RolePermission> result = rolePermissionService.getRolePermissionByPerId(idListVO.getIds());
        if (!CollectionUtils.isEmpty(result) && result.size() > 1) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_UNION_ROLE_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        // 只有自己关联的时候可以删除
        RolePermission query = result.get(0);
        if (query.getRoleId()!=(roleId)) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_UN_AUTH_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, systemParam.getMassage());
        }
        rolePermissionService.deleteByPrimaryKey(query.getRoleId(), query.getPermId());
        permissionService.batchDelete(idListVO.getIds());
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.DELETE_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    @PostMapping("/updatePermission")
    @OperationAnnotation(content = "修改资源")
    public BaseResponse updatePermission(HttpServletRequest request, @RequestBody Permission permission) throws Exception {
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(permission.getId()).isPresent()) {
            SystemParam systemParam = systemParamByCacheService.getValues(PermissionConstant.PER_ENUM, PermissionConstant.PER_NO_ID_PREFIX + language);
            throw new DefinitException(HttpServletResponse.SC_OK, systemParam.getMassage());
        }
        permission.setUpdateTime(new Date());
        permission.setUpdatedBy(MayiktJwtUtils.getUsername(request, secretKey));
        permissionService.updateByPrimaryKeySelective(permission);
        SystemParam systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

}
